<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">新增项目</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="项目名">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.project }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="项目类型">
        <template #default="scope">
          {{ scope.row.projectname }}
        </template>
      </el-table-column>
      <el-table-column label="项目需求">
        <template #default="scope">
          {{ scope.row.requirement }}
        </template>
      </el-table-column>
      <el-table-column label="项目状态">
        <template #default="scope">
          {{ scope.row.type == 0 ? '待分配' : scope.row.type == 1 ? '已分配' : '已完成' }}
        </template>
      </el-table-column>
      <el-table-column label="项目归属">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="起始时间">
        <template #default="scope">
          {{ dayjs(scope.row.start).format('YYYY年MM月DD日 HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="项目附件">
        <template #default="scope">
          <el-image
            v-if="scope.row.extend"
            style="width: 100px; height: 100px"
            :src="'/api/' + scope.row.extend.split(',')[0]"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            preview-teleported="true"
            :preview-src-list="
              scope.row.extend.split(',').map((item: any) => {
                return '/api/' + item
              })
            "
            :initial-index="4"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="新增项目" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="项目名" prop="project">
          <el-input v-model="ruleForm.project" />
        </el-form-item>

        <el-form-item label="项目类型" prop="projectname">
          <el-input v-model="ruleForm.projectname" />
        </el-form-item>
        <el-form-item label="项目需求" prop="requirement">
          <el-input v-model="ruleForm.requirement" />
        </el-form-item>

        <el-form-item label="起始时间" prop="start">
          <el-date-picker v-model="ruleForm.start" type="datetime" placeholder="请选择起始时间" />
        </el-form-item>

        <el-form-item label="项目归属">
          <el-select v-model="posts" placeholder="请选择项目经理">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目附件" prop="extend">
          <el-upload
            ref="uploadRef"
            name="filename"
            v-model:file-list="fileList"
            class="upload-demo"
            action="/api/uploads"
            multiple
            :limit="3"
            :auto-upload="false"
            :on-success="success"
          >
            <el-button type="primary">点击选择附件</el-button>
            <template #tip>
              <div class="el-upload__tip">文件大小不能超过 500KB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br />
    <div class="demo-pagination-block">
      <el-pagination
        @change="change"
        v-model:current-page="pageindex"
        v-model:page-size="pageNum"
        background
        layout="prev, pager, next"
        :total="total"
      />
    </div>

    <el-dialog v-model="editDialogVisible" title="编辑项目" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="项目名称" prop="Editprojectname">
          <el-input v-model="Editprojectname" disabled />
        </el-form-item>
        <el-form-item label="项目归属">
          <el-select v-model="Editposts" :placeholder="tipType1">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import {
  projectsQuery,
  projectsAdd,
  projectsDel,
  projectsAllquery,
  projectsUpdate
} from '../services/projectService'
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules, UploadInstance } from 'element-plus'
// import { menuQuery } from '../services/menuService'
import { userQuery } from '../services/userService'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 编辑
let editDialogVisible = ref<boolean>(false)
let tipType: any = ref('')
let tipType1: any = ref('')
let Editposts: any = ref('')
let EditId: any = ref('')
let Editprojectname = ref('')

// 分页
let pageindex = ref(1) //显示第几页
let pageNum = ref(5) //每页显示数据
let total = ref() //数据总数

const change = (val1: number, val2: number) => {
  pageindex.value = val1
  search()
}

interface User {
  _id?: string
  userpwd: string
  type: number
  project: String
  username: string
}
// 岗位
let posts = ref('')
const options = ref<any>([])

let dialogVisible = ref<boolean>(false) //控制显示
const ruleFormRef = ref<FormInstance>() //表单元素
const tableData = ref<Array<User>>([])
const ruleForm = reactive({
  //数据
  project: '',
  projectname: '',
  requirement: '',
  username: '',
  start: '',
  reason: '',
  end: ''
})

let fileList = ref<any>([]) //文件集合
let fileSuccessList = ref<any>([]) //上传成功文件的集合
const uploadRef = ref<UploadInstance>() //组件名称

// 规则
const rules = reactive<FormRules<typeof ruleForm>>({
  project: [{ required: true, message: '项目名不能为空', trigger: 'blur' }],
  start: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  projectname: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
  requirement: [{ required: true, message: '项目需求不能为空', trigger: 'blur' }]
})

let success = async (res: any) => {
  if (res.code == 200) {
    fileSuccessList.value.push(res.url)
    if (fileSuccessList.value.length == fileList.value.length) {
      let params = {
        project: ruleForm.project,
        projectname: ruleForm.projectname,
        requirement: ruleForm.requirement,
        start: ruleForm.start,
        reason: ruleForm.reason,
        extend: fileSuccessList.value.join(',')
      }
      // 没有选择附件
      if (posts.value) {
        params.userid = posts.value
        params.type = 1
      }
      let res = await projectsAdd(params)
      if (res.data.code == 200) {
        search()
        ElMessage(res.data.msg)
        ruleFormRef.value?.resetFields() //清空
        fileList.value = []
        fileSuccessList.value = []
        dialogVisible.value = false //隐藏
      } else {
        ElMessage(res.data.msg)
      }
    }
  }
}

onMounted(async () => {
  search()
})

let search = async () => {
  let res = await projectsAllquery({ pageindex: pageindex.value, pageNum: pageNum.value })
  tableData.value = res.data.data
  total.value = res.data.total

  // 新增岗位类目
  let res2 = await userQuery({ type: [1] })
  options.value = res2.data.data.map((item: any) => {
    return { label: item.username, value: item._id }
  })
}

//编辑事件
const handleEdit = (index: number, row: User) => {
  editDialogVisible.value = true
  EditId.value = row._id
  Editprojectname.value = row.project
  tipType.value = row.project
  tipType1.value = row.username ? row.username : '请选择项目经理'
}

//删除事件
const handleDelete = async (index: number, row: User) => {
  let _id = row._id
  let res = await projectsDel({
    _id
  })
  if (res.data.code == 200) {
    tableData.value = tableData.value.filter((item) => {
      return item._id != _id
    })
    search()
  }
}

//新增项目
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (editDialogVisible.value) {
        // 更新
        let userid = Editposts.value
        let type = 1
        let res2 = await projectsUpdate({ userid, type, _id: EditId.value })
        if (res2.data.code == 200) {

          // 页面同步
          tableData.value.forEach((item: any) => {            
            if (item._id == res2.data.data[0]._id) {
              item.type = 1
              item.username = res2.data.data[0].username
              item.userid = res2.data.data[0].userid
            }
          })

          ElMessage(res2.data.msg)
          resetForm(formEl) //重置表单
          editDialogVisible.value = false //隐藏
        } else {
          ElMessage(res2.data.msg)
        }
      } else {
        if (fileList.value.length) {
          //表示选了附件
          uploadRef.value!.submit() //上传
        } else {
          let params = {
            project: ruleForm.project,
            projectname: ruleForm.projectname,
            requirement: ruleForm.requirement,
            start: ruleForm.start
          }
          // 没有选择附件
          if (posts.value) {
            params.userid = posts.value
            params.type = 1
          }
          let res = await projectsAdd(params)
          if (res.data.code == 200) {
            search()
            ElMessage(res.data.msg)
            resetForm(formEl) //重置表单
            dialogVisible.value = false //隐藏
          } else {
            ElMessage(res.data.msg)
          }
        }
      }
    } else {
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
  editDialogVisible.value = false
}
</script>
